package cn.faifai.tagapi.service.BackgroundServices.FileWatcher;

import org.springframework.scheduling.annotation.Async;

import java.io.IOException;
import java.nio.file.*;


public interface FileWatcherService {


    @Async
    default void start(Path path) throws IOException {
        WatchService watchService = FileSystems.getDefault().newWatchService();
        path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);

        while (true) {
            WatchKey key;
            try {
                key = watchService.take();
            } catch (InterruptedException e) {
                return;
            }

            for (WatchEvent<?> event : key.pollEvents()) {
                WatchEvent.Kind<?> kind = event.kind();

                if (kind == StandardWatchEventKinds.ENTRY_CREATE){
                    /**
                     * 如果你正在监视目录 C:\myDir 并在其中创建了一个名为 newFile.txt 的文件，
                     * 则 event.context() 将返回 newFile.txt 而不是 C:\myDir\newFile.txt。
                     */
                    Path createdFile = (Path) event.context();
                    Path absolute = path.resolve(createdFile);
                    this.afterCreate(absolute);
                }

                if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
                    Path modifiedFile = (Path) event.context();
                    Path absolute = path.resolve(modifiedFile);
                    this.afterModify(absolute);
                }

                if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
                    Path deletedFile = (Path) event.context();
                    Path absolute = path.resolve(deletedFile);
                    this.afterDelete(absolute);
                }
            }

            if (!key.reset()) {
                break;
            }
        }
    }

    public void afterModify(Path path);
    public void afterCreate(Path path);
    public void afterDelete(Path path);
}
